package com.zfl;

import java.util.ArrayList;
import java.util.List;

public class Permutation {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        List<List<Integer>> lists = new Permutation().permute(nums);
        System.out.println("lists = " + lists);
    }

    public List<List<Integer>> permute(int[] nums) {
        //存储所有排列情况的List
        List<List<Integer>> lists = new ArrayList<>();

        //创建一个标记数组
        boolean[] used = new boolean[nums.length];
        ArrayList<Integer> cur = new ArrayList<>();
        backtrace(nums, cur, used, lists);
        return lists;
    }

    private void backtrace(int[] nums, ArrayList<Integer> current, boolean[] used, List<List<Integer>> lists) {
        if (current.size() == nums.length) {
            lists.add(new ArrayList<>(current));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            //优先排除特例
            if (used[i]) {
                continue;
            }
            current.add(nums[i]);
            used[i] = true;
            backtrace(nums, current, used, lists);
            current.remove(current.size() - 1);
            used[i] = false;
        }
    }
}
